﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TriviaModel;
using System.Data.Entity;
using System.Drawing;
using System.Windows.Media.Imaging;
using System.IO;

namespace TriviaDal
{
    public class TriviaDalClass
    {
        const int NUMBER_OF_GAME_QUESTIONS = 3;
        static Random rnd = new Random();

        public List<QuestionCalss> GetQusetions1(string difficulty, string qtype)
        {
            List<QuestionCalss> qList = new List<QuestionCalss>();
            using (var context = new TriviaDBEntities())
            {
                QuestionCalss q = null;
                var listId = context.Questions.Where(item => item.Dificulty.DifficultyLevel == difficulty &&
                    item.Type.TypeString == qtype).Select(item => item.ID).ToList();
                if (listId.Count > 0)
                {
                    for (int i = 0; i < NUMBER_OF_GAME_QUESTIONS; i++)
                    {
                        var n = listId[rnd.Next(0, listId.Count)];
                        listId.Remove(n);
                        q = Converter.ToClassQuestionConverter(context.Questions.FirstOrDefault(item => item.ID == n));
                        q.Answers = GetAnsweres(q.Id);
                        qList.Add(q);
                    }
                }
            }
            return qList;
        }

        public List<QuestionCalss> GetQusetions(string difficulty, string qtype)
        {
            List<QuestionCalss> qList = new List<QuestionCalss>();
            using (var context = new TriviaDBEntities())
            {
                int id;
                QuestionCalss q = null;
                var listId = context.Questions.Where(item => item.Dificulty.DifficultyLevel == difficulty &&
                    item.Type.TypeString == qtype).Select(item => item.ID).ToList();
                if (listId.Count > 0)
                {
                    for (int i = 0; i < NUMBER_OF_GAME_QUESTIONS; i++)
                    {
                        id = listId[rnd.Next(0, listId.Count)];
                        listId.Remove(id);
                        q = Converter.ToClassQuestionConverter(context.Questions.FirstOrDefault(item => item.ID == id));
                        q.Answers = GetAnsweres(q.Id);
                        qList.Add(q);
                    }

                }
            }
            return qList;
        }

        /// <summary>
        /// returns answers to all questions,
        /// </summary>
        /// <param name="questionsId">parametrs the client sends to get the answeres</param>
        /// <returns></returns>
        public List<AnswerCalss> GetAnsweres(int id)
        {
            List<AnswerCalss> aList = new List<AnswerCalss>();

            using (var context = new TriviaDBEntities())
            {
                Answer a = null;
                var AList = context.Answers.Where(x => x.Question.ID == id).ToList();
                if (AList.Count >= 4)
                {
                    for (int i = 0; i < 4; i++)
                    {

                        a = AList[rnd.Next(0, AList.Count)];
                        AList.Remove(a);
                        aList.Add(Converter.ToClassAnswerConverter(a));
                    }
                }
            }

            return aList;
        }

        /// <summary>
        /// inserts user to the db and returns to the client if its an existing user or not
        /// </summary>
        /// <param name="name"></param>
        /// <param name="_password"></param>
        /// <returns></returns>
        public bool InsertUser(string name, string _password)
        {
            bool IsExits = false;
            User user = null;
            using (var context = new TriviaDBEntities())
            {
                user = context.Users.FirstOrDefault(item => item.UserName == name && item.Password == _password);
                if (user == null)
                {
                    user = new User() { UserName = name, Password = _password };
                    context.Users.AddObject(user);
                    context.SaveChanges();
                }
                else IsExits = true;
            }
            return IsExits;

        }
        /// <summary>
        /// returns all topics of questions
        /// </summary>
        /// <returns></returns>
        public List<string> GetTopics()
        {
            using (var context = new TriviaDBEntities())
            {
                return (from x in context.Types select x.TypeString).ToList();
            }
        }
        /// <summary>
        /// returns all difficulties of questions
        /// </summary>
        /// <returns></returns>
        public List<string> GetDificulties()
        {
            using (var context = new TriviaDBEntities())
            {
                return (from x in context.Dificulties select x.DifficultyLevel).ToList();
            }
        }
        /// <summary>
        /// returns to the client if he chose the right answer
        /// </summary>
        /// <param name="answerId"></param>
        /// <returns></returns>
        public bool IsTheAnswerRight(int answerId, int questionnId)
        {
            using (var context = new TriviaDBEntities())
            {
                return context.Answers.Any(item => item.Id == answerId && item.Question.ID == questionnId && item.IsRightAnswere == true);
            }
        }
        /// <summary>
        /// returns user name and score
        /// </summary>
        /// <returns></returns>
        public List<UserClass> ReturnUsers()
        {
            var list = new List<UserClass>();
            using (var context = new TriviaDBEntities())
            {

                foreach (var item in context.Users)
                    list.Add(Converter.ToClassUserConverter(item));

            }
            return list.OrderByDescending(item => item.score).ToList();
        }
        /// <summary>
        /// if an existing user is playing enters the score to the db and returns score
        ///if not returns score.
        /// </summary>
        /// <param name="timeScore"></param>
        /// <param name="userNam"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public void CalcAndGetScore(int score, string userNam, string password)
        {
            if (userNam != null && password != null)
            {
                using (var context = new TriviaDBEntities())
                {
                    context.Users.FirstOrDefault(item => item.UserName == userNam && item.Password == password).Score = (int)score;
                    context.SaveChanges();
                }
            }

        }

        public bool AddTopic(string topic)
        {
            bool isTypeExits = false;
            using (var context = new TriviaDBEntities())
            {
                TriviaModel.Type t = context.Types.FirstOrDefault(item => item.TypeString == topic);
                if (t == null)
                {
                    t = new TriviaModel.Type() { TypeString = topic };
                    context.Types.AddObject(t);
                    context.SaveChanges();
                }
                else
                    isTypeExits = true;
            }

            return isTypeExits;

        }

        public bool AddDifficulty(string difficulty)
        {
            bool isDifficultyExists = false;
            using (var context = new TriviaDBEntities())
            {
                TriviaModel.Dificulty d = context.Dificulties.FirstOrDefault(item => item.DifficultyLevel == difficulty);
                if (d == null)
                {
                    d = new TriviaModel.Dificulty() { DifficultyLevel = difficulty };
                    context.Dificulties.AddObject(d);
                    context.SaveChanges();
                }
                else
                    isDifficultyExists = true;
            }

            return isDifficultyExists;
        }

        public int AddQuestion(QuestionCalss question)
        {
            using (var context = new TriviaDBEntities())
            {
                context.Questions.AddObject(Converter.ToEntityQuestionConverter(question));
                context.SaveChanges();
                return context.Questions.FirstOrDefault(item => item.QuestionString == question.QuestionString).ID;
            }
        }


        public void AddAnswers(List<AnswerCalss> answers)
        {
            using (var context = new TriviaDBEntities())
            {
                foreach (var item in answers)
                {
                    context.Answers.AddObject(Converter.ToEntityAnswerConverter(item));
                    context.SaveChanges();
                }
            }
        }

        public int GetDifficultyId(string difficultyLevel)
        {
            using (var context = new TriviaDBEntities())
            {
                return context.Dificulties.FirstOrDefault(item => item.DifficultyLevel == difficultyLevel).ID;
            }
        }

        public int GetTypeId(string Typestring)
        {
            using (var context = new TriviaDBEntities())
            {
                return context.Types.FirstOrDefault(item => item.TypeString == Typestring).Id;
            }
        }

        //public byte[] ConvertImageToByteArray()
        //{
        //    using (var context = new TriviaDBEntities())
        //    {
        //        byte[] data;
        //        data = System.IO.File.ReadAllBytes(@"C:\Users\rahelly\Desktop\Final 29.5.2011\TriviaGameRahelly\TriviaViews\Images\images.jpg");
        //        Question q = new Question() { QuestionImage = data };
        //        context.Questions.AddObject(q);
        //        context.SaveChanges();
        //        return data;

        //    }


        //}

        //public BitmapSource ConvertToImageSource()
        //{

        //    byte[] data;
        //    data = System.IO.File.ReadAllBytes(@"C:\Users\rahelly\Desktop\Final 29.5.2011\TriviaGameRahelly\TriviaViews\Images\images.jpg");

        //    using (MemoryStream ms = new MemoryStream(data))
        //    {
        //        var decoder = BitmapDecoder.Create(ms,
        //            BitmapCreateOptions.PreservePixelFormat,
        //            BitmapCacheOption.OnLoad);
        //        return decoder.Frames[0];
        //    }

        //}

    }
}
